package com.lalilu.lread.adapter

import android.net.Uri
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.facebook.drawee.view.SimpleDraweeView
import com.lalilu.lread.entity.LBook
import com.lalilu.lread.utils.ObjectUtils

@BindingAdapter("imageUriString")
fun SimpleDraweeView.bindImageByFresco(uriString: String?) {
    uriString ?: return

    setImageURI(Uri.parse(uriString), context)
}

@BindingAdapter("setPageCount")
fun ViewPager2.setPageCount(pageCount: Int?) {
    if (ObjectUtils.isNotSafe(adapter, WebViewPagerAdapter::class.java)
        || pageCount == null
    ) return

    val emptyPages = ArrayList<Int>()
    repeat(pageCount) { emptyPages.add(it) }
    (adapter as WebViewPagerAdapter).setDiffNewData(emptyPages)
}

@BindingAdapter("setDiffData")
fun RecyclerView.setDiffData(list: List<LBook>?) {
    if (ObjectUtils.isNotSafe(adapter, LBookAdapter::class.java)
        || list == null
    ) return

    (adapter as LBookAdapter).setDiffNewData(list.toMutableList())
}

@BindingAdapter("spanCount")
fun RecyclerView.setSpanCount(spanCount: Int?) {
    if (ObjectUtils.isNotSafe(layoutManager, GridLayoutManager::class.java)
        || spanCount == null
    ) return

    val layoutManager = layoutManager as GridLayoutManager
    layoutManager.spanCount = spanCount
    layoutManager.requestSimpleAnimationsInNextLayout()
}

